package com.taxshare.seller.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.taxshare.mybatis.pager.PageHelp;
import com.taxshare.mybatis.pager.PageRequest;
import com.taxshare.response.beans.Response;
import com.taxshare.seller.entity.GoodsManageEntity;
import com.taxshare.seller.entity.SellerDetialMergeEntity;
import com.taxshare.seller.mapper.SellerDetialMergeMapper;
import com.taxshare.tools.token.UserInfoUtil;
import com.taxshare.tools.util.UUIDUitl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName: SellerDetialService
 * @Description:
 * @author: Hai
 * @date: 2021/7/12 9:57
 */
@Service
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED)
@Slf4j
public class SellerDetialMergeService extends ServiceImpl<SellerDetialMergeMapper, SellerDetialMergeEntity> {

    @Autowired
    private GoodsManageService goodsManageService;

    /**
     * 开票规则模板分页查询
     * @param query
     * @return
     */
    public Response getSellerDetialMergeList(PageRequest<SellerDetialMergeEntity> query) {
        QueryWrapper<SellerDetialMergeEntity> queryWrapper = new QueryWrapper<>();
        if (StrUtil.isNotBlank(query.getInfo().getProjectCodeMax())) {
            queryWrapper.like("project_code_max", query.getInfo().getProjectCodeMax());
        }
        if (StrUtil.isNotBlank(query.getInfo().getProjectMax())) {
            queryWrapper.like("project_max", query.getInfo().getProjectMax());
        }
        if (StrUtil.isNotBlank(query.getInfo().getIsMergeDetialTaxRate())) {
            queryWrapper.eq("is_merge_detial_tax_rate", query.getInfo().getIsMergeDetialTaxRate());
        }
        if (StrUtil.isNotBlank(query.getInfo().getIsMergeDetialGoodsName())) {
            queryWrapper.eq("is_merge_detial_goods_name", query.getInfo().getIsMergeDetialGoodsName());
        }
        if (StrUtil.isNotBlank(query.getInfo().getIsMergeCategoryName())) {
            queryWrapper.eq("is_merge_category_name", query.getInfo().getIsMergeCategoryName());
        }
        queryWrapper.orderByDesc("create_time");
        IPage<SellerDetialMergeEntity> result = PageHelp.siamplePage(this, queryWrapper, query.getPage(), SellerDetialMergeEntity.class);
        return Response.success(result);
    }

    /**
     * 新增
     * @param entity
     * @return
     */
    public Response addSellerDetialMerge(SellerDetialMergeEntity entity){
        entity.setUuid(UUIDUitl.UUID32(false));
        Response resp = checkProject(entity);
        if(!resp.SUCCESS.equals(resp.getCode())){
            return resp;
        }
        entity.setCreateUserid(UserInfoUtil.getUserID());
        entity.setUpdateUserid(UserInfoUtil.getUserID());
        entity.setCreateTimeStr(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        entity.setCreateUserName(UserInfoUtil.getUserNickName());
        entity.setUpdateTimeStr(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        baseMapper.insert(entity);
        return Response.success();
    }

    /**
     * 修改
     * @param entity
     * @return
     */
    public Response updateSellerDetialMerge(SellerDetialMergeEntity entity){
        Response resp = checkProject(entity);
        if(!resp.SUCCESS.equals(resp.getCode())){
            return resp;
        }
        entity.setUpdateUserid(UserInfoUtil.getUserID());
        entity.setUpdateTimeStr(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        baseMapper.updateById(entity);
        return Response.success();
    }

    /**
     * 校验保存
     * @param entity
     * @return
     */
    private Response checkProject(SellerDetialMergeEntity entity){
        if(StrUtil.isBlank(entity.getProjectCodeMax())){
            return Response.error("SEL_107");
        }
        QueryWrapper<SellerDetialMergeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("project_code_max",entity.getProjectCodeMax());
        queryWrapper.notIn("uuid",entity.getUuid());
        if(baseMapper.selectCount(queryWrapper) > 0){
            return Response.error("SEL_019");
        }
        if(StrUtil.isBlank(entity.getIsMergeDetialGoodsName()) && StrUtil.isBlank(entity.getIsMergeDetialTaxRate())){
            return Response.error("SEL_107");
        }
        if("1".equals(entity.getIsMergeDetialGoodsName()) && "1".equals(entity.getIsMergeDetialTaxRate())){
            return Response.error("SEL_017");
        }
        if("1".equals(entity.getIsMergeDetialTaxRate())){
            //1.判断此项目是否存不征税商品 零税率标识 空为正常税率 1 免税2 不征税 3普通零税率
            QueryWrapper<GoodsManageEntity> queryWrapperBzs = new QueryWrapper<>();
            queryWrapperBzs.eq("project_code",entity.getProjectCodeMax());
            queryWrapperBzs.eq("tax_rate_mark","2");
            if(goodsManageService.count(queryWrapperBzs) > 1){
                return Response.error("SEL_032");
            }
            //2.判断此项目是否存普通零税率商品
            QueryWrapper<GoodsManageEntity> queryWrapperLsv = new QueryWrapper<>();
            queryWrapperLsv.eq("project_code",entity.getProjectCodeMax());
            queryWrapperLsv.eq("tax_rate_mark","3");
            if(goodsManageService.count(queryWrapperBzs) > 1){
                return Response.error("SEL_033");
            }
            //3.判断此项目是否存其他税率商品
            QueryWrapper<GoodsManageEntity> queryWrapperPtsl = new QueryWrapper<>();
            queryWrapperPtsl.eq("project_code",entity.getProjectCodeMax())
            .and(wrapper ->wrapper.eq("tax_rate_mark","").or().isNull("tax_rate_mark"));
            //queryWrapperPtsl.eq("tax_rate_mark","");
            List<GoodsManageEntity> goodsList = goodsManageService.list(queryWrapperPtsl);
            List<List<GoodsManageEntity>> newGoodsList = new ArrayList<>();
            goodsList.stream().collect(Collectors.groupingBy(GoodsManageEntity::getTaxRate, Collectors.toList()))
                    .forEach((paymentName, fooListByName) -> {
                                newGoodsList.add(fooListByName);
                            }
                    );
            for(List<GoodsManageEntity> list:newGoodsList){
                if(list.size() > 1){
                    return Response.error("SEL_034");
                }
            }
        }
        return Response.success();
    }

    /**
     * 删除
     * @param uuid
     * @return
     */
    public Response delSellerDetialMerge(String uuid){
        baseMapper.deleteById(uuid);
        return Response.success();
    }
}
